//
//  VPDownloadModel.m
//  VPDownloadManager
//
//  Created by vernepung on 16/3/10.
//  Copyright © 2016年 vernepung. All rights reserved.
//

#import "VPDownloadModel.h"
#import "VPDownloadMacro.h"
#import "NSString+Additional.h"
#import "VPHTTPRequestOperationManager.h"

@interface VPDownloadModel()

@property (nonatomic, copy) NSString *fileTempPath;

@property (nonatomic, copy) NSString *filePath;
// 下载任务
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
// 断点续传需要设置这个数据
@property (nonatomic, strong) NSData *resumeData;
// 手动取消当做暂停
@property (nonatomic, assign) BOOL manualCancle;

@end
@implementation VPDownloadModel
@synthesize fileTempPath = _fileTempPath, filePath = _filePath;

#pragma mark - NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.resumeData forKey:NSStringFromSelector(@selector(resumeData))];
    [aCoder encodeObject:self.mainId forKey:NSStringFromSelector(@selector(mainId))];
    [aCoder encodeObject:self.fileUrl forKey:NSStringFromSelector(@selector(fileUrl))];
    [aCoder encodeObject:self.fileName forKey:NSStringFromSelector(@selector(fileName))];
    [aCoder encodeObject:self.title forKey:NSStringFromSelector(@selector(title))];
    [aCoder encodeObject:self.categoryTitle forKey:NSStringFromSelector(@selector(categoryTitle))];
    [aCoder encodeObject:self.imageUrlString forKey:NSStringFromSelector(@selector(imageUrlString))];
    [aCoder encodeObject:self.suffix forKey:NSStringFromSelector(@selector(suffix))];
    [aCoder encodeObject:self.filePath forKey:NSStringFromSelector(@selector(filePath))];
    [aCoder encodeObject:self.fileTempPath forKey:NSStringFromSelector(@selector(fileTempPath))];
    [aCoder encodeObject:@(self.downloadState) forKey:NSStringFromSelector(@selector(downloadState))];
    [aCoder encodeObject:@(self.readedBytes) forKey:NSStringFromSelector(@selector(readedBytes))];
    [aCoder encodeObject:@(self.totalBytes) forKey:NSStringFromSelector(@selector(totalBytes))];
    [aCoder encodeObject:self.typeName forKey:NSStringFromSelector(@selector(typeName))];
    [aCoder encodeObject:@(self.isDownloadCenterValid) forKey:NSStringFromSelector(@selector(isDownloadCenterValid))];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.mainId = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(mainId))];
        self.resumeData = [aDecoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(resumeData))];
        self.fileUrl = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(fileUrl))];
        self.fileName = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(fileName))];
        self.title = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(title))];
        self.categoryTitle = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(categoryTitle))];
        self.imageUrlString = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(imageUrlString))];
        self.suffix = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(suffix))];
        self.filePath = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(filePath))];
        self.fileTempPath = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(fileTempPath))];
        self.downloadState = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(downloadState))] integerValue];
        self.readedBytes = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readedBytes))] longLongValue];
        self.totalBytes = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytes))] longLongValue];
        self.typeName = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(typeName))];
        self.isDownloadCenterValid = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(isDownloadCenterValid))] boolValue];
    }
    return self;
}

- (BOOL)isCompleted
{
    if (self.downloadState == kVPDownloadStateCompleted)
    {
        return YES;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
    {
        self.readedBytes = self.totalBytes;
        return YES;
    }
    if (self.totalBytes > 0 && self.readedBytes > 0 &&  self.readedBytes == self.totalBytes)
    {
        return YES;
    }
    return NO;
}

- (void)removeFiles{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath: getDownloadFilesPath([VPHTTPRequestOperationManager currentMainPath],self.filePath)])
    {
        [fileManager removeItemAtPath:getDownloadFilesPath([VPHTTPRequestOperationManager currentMainPath],self.filePath) error:nil];
    }
    if ([fileManager fileExistsAtPath:getDownloadTempFilePath([VPHTTPRequestOperationManager currentMainPath], self.fileTempPath)])
    {
        [fileManager removeItemAtPath:getDownloadTempFilePath([VPHTTPRequestOperationManager currentMainPath], self.fileTempPath) error:nil];
    }
}

- (NSString *)fileTempPath
{
    if ([Helper isBlankString:_fileTempPath])
    {
        //        _fileTempPath = [[getDownloadTempFolderPath([VPHTTPRequestOperationManager currentMainPath]) stringByAppendingPathComponent:[_fileUrl md5]] copy];
        _fileTempPath = [[self.mainId md5] copy];
    }
    return _fileTempPath;
}

- (NSString *)filePath
{
    if ([Helper isBlankString:_filePath])
    {
        NSString *filePathStr = [self.mainId md5];
        if (self.suffix && self.suffix.length) {
            filePathStr = [NSString stringWithFormat:@"%@.%@", filePathStr, self.suffix];
        }
        //        _filePath = [[getDownloadFilesFolderPath([VPHTTPRequestOperationManager currentMainPath]) stringByAppendingPathComponent:filePathStr] copy];
        _filePath = [filePathStr copy];
    }
    return _filePath;
}

- (NSString *)fullFilePath {
    return getDownloadFilesPath([VPHTTPRequestOperationManager currentMainPath],self.filePath);
}

- (NSString *)suffix{
    if ([Helper isBlankString:_suffix]){
        if (![Helper isBlankString:self.fileUrl]) {
            id param = [self getParameterOfUrl:self.fileUrl];
            if ([param isKindOfClass:[NSDictionary class]]&&[[param allKeys] containsObject:@"security-token"]) {
                /*AliCloud*/
                NSString *localhostUrl =  param[@"localhost"];
                NSRange range = [localhostUrl rangeOfString:@"." options:NSBackwardsSearch];
                if (range.location != NSNotFound) {
                    _suffix = [localhostUrl substringFromIndex:range.location+1];
                }
            } else{
                NSRange range = [self.fileUrl rangeOfString:@"." options:NSBackwardsSearch];
                if (range.location != NSNotFound) {
                    _suffix = [self.fileUrl substringFromIndex:range.location+1];
                }
            }
        }
    }
    return _suffix;
}

- (long long)readedBytes
{
    if (_readedBytes <= 0)
    {
        _readedBytes = [[[NSFileManager defaultManager] attributesOfItemAtPath:self.fileTempPath error:nil] fileSize];
    }
    return _readedBytes;
}

- (void)setDownloadState:(kVPDownloadState)downloadState
{
    if (_downloadState != downloadState)
    {
        _downloadState = downloadState;
    }
}

- (NSString *)mainId
{
    @throw [[NSException alloc] initWithName:@"error mainId" reason:@"you must be extends this property!!!" userInfo:@{@"class":@"VPDownloadModel"}];
}

- (BOOL)isEqual:(id)object
{
    if (self == object)
        return YES;
    if (!object || ![object isKindOfClass:[self class]])
        return NO;
    return [[self mainId] isEqualToString:[(VPDownloadModel *)object mainId]];
}


- (id)getParameterOfUrl:(NSString *)urlVlaueString
{
    NSRange range = [urlVlaueString rangeOfString:@"?"];
    if (range.length) {
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        NSString *parameterUrl = [urlVlaueString substringFromIndex:range.location+1];
        NSArray *parameterArr = [parameterUrl componentsSeparatedByString:@"&"];
        for (NSString *parameter in parameterArr) {
            NSArray *parameterBoby = [parameter componentsSeparatedByString:@"="];
            if (parameterBoby.count == 2) {
                [dictionary setObject:parameterBoby[1] forKey:parameterBoby[0]];
            } else{
                return @"Illegal character";
            }
        }
        NSString *localhostString = [urlVlaueString substringToIndex:range.location];
        [dictionary setObject:localhostString forKey:@"localhost"];
        return dictionary;
    } else{
        return @"No parameters";
    }
}


@end
